package com.eco.fanliapp.job.delayjob;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 大额延迟定时扫描
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DelayPddTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(DelayPddTask.class);

    @Autowired
    private IPddUserOrderService iPddUserOrderService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private IPddOrderDetailService iPddOrderDetailService;
    @Autowired
    private ISySwitchService iSySwitchService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private IAppWxWithdrawalService iAppWxWithdrawalService;

    public DelayPddTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行拼多多大额延迟定时扫描任务-DelayPddTask：executeCount=" + executeCount + "--startTime=" + startTime);
        Long stime = DateFormatUtils.getStartTime();
        Long etime = DateFormatUtils.getEndTime();
        try {
            //获取所有满足条件的order
            List<PddUserOrder> userOrders = iPddUserOrderService.selectPddLargeAmountYesList(stime, etime);
            for (PddUserOrder pddUserOrder : userOrders) {
                AppUser user = iAppUserService.selectAppUserByUserId(pddUserOrder.getUserId());
                QueryWrapper<PddOrderDetail> queryOrderDetail = new QueryWrapper<>();
                queryOrderDetail.eq("order_sn", pddUserOrder.getOrderSn());
                PddOrderDetail pddOrderDetail = iPddOrderDetailService.getOne(queryOrderDetail);
                if (user != null && user.getEnable() != 0) {//0=禁用
                    PddUserOrder pddUserOrderNew = new PddUserOrder();
                    pddUserOrderNew.setTableId(pddUserOrder.getTableId());
                    pddUserOrderNew.setOrderSettleStatus(2);
                    Boolean i = iPddUserOrderService.updateById(pddUserOrderNew);
                    BigDecimal beforeBalance = user.getBalance();
                    if (i) {
                        BigDecimal commission = new BigDecimal(pddUserOrder.getCommission()).divide(new BigDecimal("100"));
                        int ii = iAppUserService.updateAppUseraddbalance(pddUserOrder.getUserId(), commission);
                        log.info("message{}自己{}", pddUserOrder.getUserId(), commission);
                        log.info("拼多多商品大额延迟开始发送消息{}", ii);
                        if (ii > 0 && isSendMsg(8)) {
                            //新增用户余额变动日志记录
                            String goodName = "";
                            if(pddOrderDetail != null && pddOrderDetail.getGoodsName() != null){
                                goodName = pddOrderDetail.getGoodsName();
                            }else {
                                goodName = pddUserOrder.getOrderSn();
                            }
                            syUserMoneyLogService.addSyUserMoneyLog(user.getUserId(), beforeBalance, commission, "拼多多商品大额延迟", 2, 0);
                            iAppNewsLogService.newsType(pddUserOrder.getUserId(),
                                    NewsEnumLog.NEWS_AWARD_BIGDELAY.getNewsType(),
                                    commission,"拼多多", goodName, commission.toString());
                        }

                        try {
                            //公众号发送消息
                            // TODO: 结算成功公众号提醒
                            String time = DateFormatUtils.dateToString(new Date());
                            ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(user, "30006", pddUserOrder.getOrderSn(), commission.toString(), time, user.getWechatNickname());
                            log.info("公众号发消2息返回结果{}", JSONObject.toJSONString(result));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }

                log.info("扫描到{}订单，金额为{}，用户为{}，结算状态{}",
                        pddUserOrder.getOrderSn(),
                        pddUserOrder.getCommission(),
                        pddUserOrder.getUserId(),
                        pddUserOrder.getOrderSettleStatus());
            }
    } catch(Exception e) {
        e.printStackTrace();
        log.info("执行拼多多大额延迟定时扫描任务错误");
    }

    long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行拼多多大额延迟定时扫描任务-DelayPddTask：executeCount="+executeCount +"--endTime="+endTime +"--耗时="+(endTime -startTime));
}


    /**
     * 判断是不是今天
     *
     * @param s
     * @param s2
     * @return
     */
    private Boolean isToDay(Long s, Long s2) {

        return DateUtils.isSameDay(new Date(s), new Date(s2));
    }

    /**
     * 通过开关判断是否要发消息
     *
     * @return
     * @id 开关类型
     */
    private Boolean isSendMsg(int id) {
        //查询开关表是否发消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_id", id);
        SySwitch sySwitch = iSySwitchService.getOne(queryWrapper);
        if (sySwitch == null) return false;
        if (sySwitch.getState() == 1) {
            log.info("消息类型{} 消息开发送消息", id);
            return true;
        }
        log.info("消息类型{} 消息关", id);
        return false;
    }
}
